package com.oasen.learn.usercenter.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.oasen.learn.usercenter.dao.UserAuthDao;
import com.oasen.learn.usercenter.dao.UserDao;
import com.oasen.learn.usercenter.entity.UserAuthMeta;
import com.oasen.learn.usercenter.entity.UserMeta;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lsyuan on 2017/7/1.
 */
public class UserMetaDetailsService implements UserDetailsService {

    private UserDao userDao;
    private UserAuthDao userAuthDao;
    
    public UserMetaDetailsService(UserDao userMetaDao, UserAuthDao userAuthDao) {
		super();
		this.userDao = userMetaDao;
		this.userAuthDao = userAuthDao;
	}

	public UserDetails loadUserByUsername(String uname) throws UsernameNotFoundException {
		UserMeta userMeta = new UserMeta();
		userMeta = userDao.loadUserByUsername(uname);
        List<UserAuthMeta> authMetaList = userAuthDao.findListByUser(uname);
        if(userMeta != null){
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for(UserAuthMeta userAuthMeta : authMetaList){
                authorities.add(new SimpleGrantedAuthority(userAuthMeta.getUauth()));
            }
            User user = new User(userMeta.getUname(),userMeta.getUpass(),authorities);
            return user;
        }
        throw new UsernameNotFoundException("User :"+uname+" not found");
    }
}
